package com.example.shirospringboot.config;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.example.shirospringboot.mapper.SysUserMapper;
import com.example.shirospringboot.model.SysUser;

/**
 * 此realm只是用做认证使用，所以继承了AuthenticatingRealm
 */
@Component
public class UserNamePaswordRealm  extends AuthenticatingRealm {
    @Autowired
    private SysUserMapper sysUserMapper;
    
    public UserNamePaswordRealm(CredentialsMatcher matcher) {
        super((matcher));
    }
    
    //表明此Realm只是支持我们创建的UserNamePasswordRealm
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof  UserNamePasswordToken;
    }
    
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String)token.getPrincipal();
        SysUser sysUser = sysUserMapper.getAllByUsername(userName);
        if (sysUser == null) {
            throw new UnknownAccountException("用户名或密码错误");
        }
    
        if(sysUser.getLocked() != null && sysUser.getLocked()){
            throw new LockedAccountException("该用户已经被锁定");
        }
    
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(new WrapperSysUser(userName,sysUser), sysUser.getPassowrd(), sysUser.getRealName());
        simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(String.valueOf(sysUser.getUserid())));
        return simpleAuthenticationInfo;
    }
}
